<template>
  <el-card v-if="searchConfig?.length" class="search-card">
    <el-form ref="searchFormRef" :model="searchForm" :inline="true" :label-width="labelWidth">
      <div class="search-form-content">
        <!-- 基础搜索条件 -->
        <div class="search-row">
          <el-form-item
            v-for="item in basicSearchItems"
            :key="item.field"
            :label="item.label"
          >
            <!-- Select选择器 -->
            <template v-if="item.component === 'Select'">
              <el-select
                v-model="searchForm[item.field]"
                v-bind="getComponentProps(item)"
                @keyup.enter="handleSearch"
              >
                <el-option
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </template>

            <!-- DateRangePicker日期范围选择器 -->
            <template v-else-if="item.component === 'DateRangePicker'">
              <el-date-picker
                v-model="searchForm[item.field]"
                v-bind="getComponentProps(item)"
                @keyup.enter="handleSearch"
              />
            </template>

            <!-- 默认Input输入框 -->
            <template v-else>
              <el-input
                v-model="searchForm[item.field]"
                v-bind="getComponentProps(item)"
                @keyup.enter="handleSearch"
              />
            </template>
          </el-form-item>
        </div>

        <!-- 更多搜索条件 -->
        <div v-show="showMore" class="search-row more-conditions">
          <el-form-item
            v-for="item in advancedSearchItems"
            :key="item.field"
            :label="item.label"
          >
            <!-- Select选择器 -->
            <template v-if="item.component === 'Select'">
              <el-select
                v-model="searchForm[item.field]"
                v-bind="getComponentProps(item)"
                @keyup.enter="handleSearch"
              >
                <el-option
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </template>

            <!-- DateRangePicker日期范围选择器 -->
            <template v-else-if="item.component === 'DateRangePicker'">
              <el-date-picker
                v-model="searchForm[item.field]"
                v-bind="getComponentProps(item)"
                @keyup.enter="handleSearch"
              />
            </template>

            <!-- 默认Input输入框 -->
            <template v-else>
              <el-input
                v-model="searchForm[item.field]"
                v-bind="getComponentProps(item)"
                @keyup.enter="handleSearch"
              />
            </template>
          </el-form-item>
        </div>

        <!-- 展开/收起控制器 -->
        <div v-if="hasAdvancedSearch" class="divider-wrapper" @click="toggleMore">
          <div class="divider-line">
            <el-icon :class="['expand-icon', { 'is-expand': showMore }]">
              <ArrowDown />
            </el-icon>
          </div>
        </div>
      </div>

      <!-- 搜索操作按钮组 -->
      <div class="action-buttons">
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'

/**
 * Props 定义
 */
const props = defineProps({
  // 搜索配置
  searchConfig: {
    type: Array,
    default: () => [],
  },
  // 标签宽度
  labelWidth: {
    type: String,
    default: '80px',
  },
})

/**
 * Emits 定义
 */
const emit = defineEmits(['search', 'reset'])

/**
 * Refs
 */
const searchFormRef = ref(null)
const showMore = ref(false)

/**
 * 搜索表单数据
 */
const searchForm = reactive(
  props.searchConfig.reduce((acc, item) => {
    acc[item.field] = item.defaultValue ?? ''
    return acc
  }, {})
)

/**
 * 计算属性
 */
// 基础搜索项
const basicSearchItems = computed(() => {
  return props.searchConfig.filter(item => !item.showInMore)
})

// 高级搜索项
const advancedSearchItems = computed(() => {
  return props.searchConfig.filter(item => item.showInMore)
})

// 是否有高级搜索项
const hasAdvancedSearch = computed(() => {
  return advancedSearchItems.value.length > 0
})

/**
 * 方法定义
 */
// 获取组件属性
const getComponentProps = (item) => {
  const commonProps = {
    placeholder: item.placeholder,
    clearable: true,
    ...item.props
  }

  // 日期范围选择器特殊处理
  if (item.component === 'DateRangePicker') {
    return {
      ...commonProps,
      type: 'daterange',
      rangeSeparator: '至',
      startPlaceholder: item.props?.startPlaceholder,
      endPlaceholder: item.props?.endPlaceholder,
      valueFormat: item.props?.valueFormat
    }
  }

  return commonProps
}

// 切换更多条件显示
const toggleMore = () => {
  showMore.value = !showMore.value
}

// 搜索
const handleSearch = () => {
  emit('search', { ...searchForm })
}

// 重置
const handleReset = () => {
  // 重置每个字段到默认值
  props.searchConfig.forEach(item => {
    searchForm[item.field] = item.defaultValue ?? ''
  })

  // 重置表单UI
  searchFormRef.value?.resetFields()

  // 触发重置事件，传递重置后的表单值
  emit('reset', { ...searchForm })
}

/**
 * 暴露方法和属性
 */
defineExpose({
  searchForm,
  searchFormRef,
  reset: handleReset,
})
</script>

<style lang="scss" scoped>
/* 搜索区域样式 */
.search-card {
  :deep(.el-card__body) {
    padding: $font-size-large;
  }

  .el-form {
    --el-form-inline-content-width: 240px;

    .search-form-content {
      position: relative;
    }

    // 搜索行样式
    .search-row {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: $font-size-base;

      &.more-conditions {
        margin-top: $font-size-base;
      }

      :deep(.el-form-item) {
        margin: 0;
        width: 100%;

        .el-form-item__content {
          width: 100%;
        }

        // 统一输入框样式
        .el-input,
        .el-select,
        .el-date-editor {
          width: 100% !important;

          .el-input__wrapper {
            width: 100%;
          }
        }

        // 日期选择器样式
        .el-date-editor.el-range-editor {
          .el-range-separator {
            padding: 0 4px;
          }
        }
      }
    }

    // 展开/收起控制器样式
    .divider-wrapper {
      position: relative;
      height: 20px;
      margin: $font-size-small 0;
      cursor: pointer;
      user-select: none;

      .divider-line {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        height: 1px;
        background: linear-gradient(
          90deg,
          transparent,
          $border-base 35%,
          $border-base 65%,
          transparent
        );
      }

      .expand-icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: transform 0.3s ease;
        color: $text-secondary;
        font-size: 12px;
        background: $bg-base;
        padding: 2px;

        &.is-expand {
          transform: translate(-50%, -50%) rotate(180deg);
          color: $primary-color;
        }
      }
    }

    // 按钮组样式
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: $font-size-base;
      margin-top: $font-size-base;

      .el-button {
        padding: 8px 24px;
        border-radius: $border-radius-medium;
        font-weight: 500;
        transition: $transition-base;

        &[type='primary'] {
          background: linear-gradient(135deg, $primary-color, rgba($primary-color, 0.8));
          border: none;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba($primary-color, 0.3);
          }

          &:active {
            transform: translateY(0);
          }
        }
      }
    }
  }
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .search-card {
    :deep(.el-card__body) {
      padding: $font-size-base;
    }

    .el-form {
      .search-form-content {
        .search-row {
          grid-template-columns: 1fr;
          gap: $font-size-small;
        }
      }

      .action-buttons {
        flex-direction: column;
        gap: $font-size-small;

        .el-button {
          width: 100%;
          height: 40px;
        }
      }
    }
  }
}
</style>
